import { createPinia, defineStore } from "pinia";
import type { toRouteType } from "@/router";

export interface CachedViewStoreState {
	cachedViewList: string[];
}

export interface CachedViewSotreActions {
	addCachedView: (this: CachedViewStoreState, view: toRouteType) => void;
	delCachedView: (this: CachedViewStoreState, view: toRouteType) => void;
	delAllCachedViews: (this: CachedViewStoreState) => void;
}

// eslint-disable-next-line @typescript-eslint/no-unused-vars
export interface CachedViewStoreGetters<T = CachedViewStoreState> {
	[key: string]: any;
}

export const useCachedViewStore = defineStore<string, CachedViewStoreState, CachedViewStoreGetters, CachedViewSotreActions>(
	"cachedView",
	{
		state: () => ({
			cachedViewList: []
		}),

		getters: {},

		actions: {
			addCachedView(this: CachedViewStoreState, view: toRouteType) {
				// 不重复添加
				if (this.cachedViewList.includes(view.name as string)) return;
				if (!view?.meta?.noCache) {
					this.cachedViewList.push(view.name as string);
				}
			},
			delCachedView(this: CachedViewStoreState, view: toRouteType) {
				const index = this.cachedViewList.indexOf(view.name as string);
				index > -1 && this.cachedViewList.splice(index, 1);
			},
			delAllCachedViews(this: CachedViewStoreState) {
				this.cachedViewList = [];
			}
		}
	}
);

export function useCachedViewStoreHook() {
	const store = createPinia();
	return useCachedViewStore(store);
}
